const app = getApp()

Page({
  /**
   * 页面的初始数据
   */
  data: {
    post: null,
    comments: [],
    commentText: '',
    isLiked: false,
    isLoadingComments: false,
    hasMoreComments: true,
    commentPageNum: 1,
    commentPageSize: 10
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    try {
      console.log('帖子详情页加载，参数:', options)
      const postId = options.id
      
      if (!postId) {
        console.error('帖子ID不存在')
        wx.showToast({
          title: '帖子ID不存在',
          icon: 'none'
        })
        setTimeout(() => {
          wx.navigateBack()
        }, 1500)
        return
      }
      
      // 从云数据库获取帖子详情
      this.loadPostDetail(postId)
      // 从云数据库获取评论列表
      this.loadComments(postId)
      // 检查用户是否已点赞
      this.checkLikeStatus(postId)
    } catch (error) {
      console.error('帖子详情页加载出错:', error)
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
    }
  },

  /**
   * 加载帖子详情
   */
  async loadPostDetail(postId) {
    wx.showLoading({
      title: '加载中...',
      mask: true
    })
    
    try {
      const db = wx.cloud.database()
      const postResult = await db.collection('posts').doc(postId).get()
      
      if (!postResult.data) {
        wx.hideLoading()
        wx.showToast({
          title: '帖子不存在',
          icon: 'none'
        })
        setTimeout(() => {
          wx.navigateBack()
        }, 1500)
        return
      }
      
      // 格式化时间
      const post = postResult.data
      post.createTime = new Date(post.createTime).toLocaleString()
      if (post.updateTime) {
        post.updateTime = new Date(post.updateTime).toLocaleString()
      }
      
      // 更新浏览量
      await db.collection('posts').doc(postId).update({
        data: {
          views: db.command.inc(1)
        }
      })
      
      this.setData({ post })
      wx.hideLoading()
    } catch (error) {
      console.error('获取帖子详情失败:', error)
      wx.hideLoading()
      wx.showToast({
        title: '获取帖子详情失败',
        icon: 'none'
      })
    }
  },

  /**
   * 检查用户是否已点赞
   */
  async checkLikeStatus(postId) {
    try {
      // 获取用户信息
      const userInfo = await wx.cloud.callFunction({
        name: 'getUserInfo'
      }).catch(() => ({ result: { openid: 'anonymous' } }))
      
      const db = wx.cloud.database()
      const _ = db.command
      
      // 查询用户点赞记录
      const likeResult = await db.collection('likes')
        .where({
          postId: postId,
          userId: userInfo.result.openid
        })
        .count()
      
      this.setData({
        isLiked: likeResult.total > 0
      })
    } catch (error) {
      console.error('检查点赞状态失败:', error)
    }
  },

  /**
   * 加载评论列表
   */
  async loadComments(postId, isLoadMore = false) {
    if (this.data.isLoadingComments) return
    
    this.setData({ isLoadingComments: true })
    
    try {
      const db = wx.cloud.database()
      const { commentPageNum, commentPageSize } = this.data
      
      const commentsResult = await db.collection('comments')
        .where({
          postId: postId
        })
        .orderBy('createTime', 'desc')
        .skip((commentPageNum - 1) * commentPageSize)
        .limit(commentPageSize)
        .get()
      
      // 格式化时间
      const newComments = commentsResult.data.map(comment => {
        comment.createTime = new Date(comment.createTime).toLocaleString()
        return comment
      })
      
      // 获取评论总数
      const countResult = await db.collection('comments')
        .where({
          postId: postId
        })
        .count()
      
      const hasMoreComments = this.data.comments.length + newComments.length < countResult.total
      
      this.setData({
        comments: isLoadMore ? [...this.data.comments, ...newComments] : newComments,
        hasMoreComments,
        commentPageNum: isLoadMore ? this.data.commentPageNum + 1 : 1,
        isLoadingComments: false
      })
    } catch (error) {
      console.error('获取评论列表失败:', error)
      this.setData({ isLoadingComments: false })
      wx.showToast({
        title: '获取评论失败',
        icon: 'none'
      })
    }
  },

  /**
   * 加载更多评论
   */
  loadMoreComments() {
    if (this.data.hasMoreComments && !this.data.isLoadingComments) {
      this.loadComments(this.data.post.id, true)
    }
  },

  /**
   * 预览图片
   */
  previewImage(e) {
    const url = e.currentTarget.dataset.url
    wx.previewImage({
      current: url,
      urls: this.data.post.images
    })
  },

  /**
   * 点赞帖子
   */
  async likePost() {
    const post = this.data.post
    const isLiked = this.data.isLiked
    
    try {
      // 获取用户信息
      const userInfo = await wx.cloud.callFunction({
        name: 'getUserInfo'
      }).catch(() => ({ result: { openid: 'anonymous' } }))
      
      const db = wx.cloud.database()
      
      if (isLiked) {
        // 取消点赞
        await db.collection('likes')
          .where({
            postId: post.id,
            userId: userInfo.result.openid
          })
          .remove()
        
        await db.collection('posts').doc(post.id).update({
          data: {
            likes: db.command.inc(-1)
          }
        })
        
        post.likes -= 1
        this.setData({ 
          post,
          isLiked: false
        })
        
        wx.showToast({
          title: '已取消点赞',
          icon: 'success'
        })
      } else {
        // 添加点赞
        await db.collection('likes').add({
          data: {
            postId: post.id,
            userId: userInfo.result.openid,
            createTime: new Date()
          }
        })
        
        await db.collection('posts').doc(post.id).update({
          data: {
            likes: db.command.inc(1)
          }
        })
        
        post.likes += 1
        this.setData({ 
          post,
          isLiked: true
        })
        
        wx.showToast({
          title: '点赞成功',
          icon: 'success'
        })
      }
    } catch (error) {
      console.error('点赞操作失败:', error)
      wx.showToast({
        title: '操作失败',
        icon: 'none'
      })
    }
  },

  /**
   * 输入评论
   */
  onCommentInput(e) {
    this.setData({
      commentText: e.detail.value
    })
  },

  /**
   * 提交评论
   */
  async submitComment() {
    const content = this.data.commentText.trim()
    if (!content) {
      wx.showToast({
        title: '请输入评论内容',
        icon: 'none'
      })
      return
    }
    
    wx.showLoading({
      title: '发送中...',
      mask: true
    })
    
    try {
      // 获取用户信息
      const userInfo = await wx.cloud.callFunction({
        name: 'getUserInfo'
      }).catch(() => ({ result: { openid: 'anonymous' } }))
      
      const db = wx.cloud.database()
      const post = this.data.post
      
      // 创建评论数据
      const commentData = {
        postId: post.id,
        content: content,
        createTime: new Date(),
        author: {
          openid: userInfo.result.openid,
          nickname: '匿名用户',
          avatar: '/assets/images/default-avatar.png'
        }
      }
      
      // 添加到云数据库
      const result = await db.collection('comments').add({
        data: commentData
      })
      
      // 更新帖子评论数
      await db.collection('posts').doc(post.id).update({
        data: {
          comments: db.command.inc(1)
        }
      })
      
      // 创建新评论对象用于本地显示
      const newComment = {
        id: result._id,
        content: commentData.content,
        author: commentData.author,
        createTime: new Date(commentData.createTime).toLocaleString()
      }
      
      // 更新本地数据
      post.comments += 1
      this.setData({
        comments: [newComment, ...this.data.comments],
        commentText: '',
        post
      })
      
      wx.hideLoading()
      wx.showToast({
        title: '评论成功',
        icon: 'success'
      })
    } catch (error) {
      console.error('评论失败:', error)
      wx.hideLoading()
      wx.showToast({
        title: '评论失败',
        icon: 'none'
      })
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: this.data.post.title,
      path: `/pages/post-detail/post-detail?id=${this.data.post.id}`
    }
  }
}) 